package us.kg.kotoriforest.springmvc.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 测试域对象相关API
 *
 * @author Kotori rotroutine@163.com
 * @since 2025/1/17
 */
@Controller
public class FieldTestController {
    // @RequestMapping("/")
    // public String index() {
    //     return "index";
    // }

    /*
        虽然在request作用域中传递数据有5种方法 但最后都会变成1种 即 ModelAndView
        其他4种最后都会封装成ModelAndView对象
     */

    @RequestMapping("/test/request/servlet")
    public String testRequestByServletApi(HttpServletRequest request) {
        request.setAttribute("key", "value");

        // return 的本质是请求转发 将该servlet的请求转发到另一个servlet或者是静态资源上
        return "success";
    }

    @RequestMapping("/test/request/modelandview")
    public ModelAndView testRequestByModelAndViewApi() {
        ModelAndView mav = new ModelAndView();
        // addObject 是向request域中放数据
        mav.addObject("key", "value");

        mav.setViewName("success");
        return mav;
    }

    @RequestMapping("/test/request/model")
    public String testRequestModelApi(Model model) {
        model.addAttribute("key", "value");
        return "success";
    }

    @RequestMapping("/test/request/map")
    public String testRequestMapApi(Map<String, Object> map) {
        map.put("key", "value");
        return "success";
    }

    @RequestMapping("/test/request/modelmap")
    public String testRequestModelMapApi(ModelMap modelMap) {
        modelMap.addAttribute("key", "value");
        return "success";
    }

    // 通过原生的SessionApi来共享数据
    @RequestMapping("/test/session")
    public String testSessionApi(HttpSession session) {
        session.setAttribute("key", "sessionValue");
        return "success";
    }

    // 通过原生的servletContextApi来共享数据
    @RequestMapping("/test/servletcontext")
    public String testServletContext(HttpSession session) {
        ServletContext servletContext = session.getServletContext();
        servletContext.setAttribute("key", "servletContextValue");
        return "success";
    }

    @RequestMapping("/test/redirect")
    public String testRedirectView() {
        return "redirect:https://baidu.com";
    }

}
